# -*- coding:utf-8 -*-

# @Time : 2022/11/22 15:11
# @Author : 快乐的小猴子
# @Version : 
# @Function : 

# -*- coding:utf-8 -*-

# @Time : 2022/11/14 10:09
# @Author : 快乐的小猴子
# @Version :
# @Function :

import requests
import settings
import os


class XinFaDi():

    def view_infos(self):
        num = input('请输入数据页码(q/Q退出)：')
        return num

    def send_infos(self, num):
        settings.DATA['current'] = num
        jsn_data = requests.post(url=settings.URL, headers=settings.HEADERS, data=settings.DATA).json()
        return jsn_data

    def show_rst(self, jsn_data):
        print('序号', '一级分类', '品名', '最低价', '平均价', '最高价', '产地', '单位', '发布日期')
        for x in range(0, len(jsn_data['list'])):
            print(x + 1, jsn_data['list'][x]['prodCat'], jsn_data['list'][x]['prodName'],
                  jsn_data['list'][x]['lowPrice'],
                  jsn_data['list'][x]['avgPrice'], jsn_data['list'][x]['highPrice'], jsn_data['list'][x]['place'],
                  jsn_data['list'][x]['unitInfo'], jsn_data['list'][x]['pubDate'].split(' ')[0])

    def verf_dir(self):
        '''
        校验文件路径是否存在，不存在则创建
        :return:
        '''
        file_path = os.getcwd() + '\\files\\'
        if not os.path.exists(file_path):
            os.makedirs(file_path)
        return file_path

    def save(self, jsn_data, num):
        with open('{}新发地菜价第{}页数据.txt'.format(self.verf_dir(), num), 'w', encoding='utf-8') as fp:
            fp.write('每页20条数据，该页为第{}页数据：\n\n'.format(num) + '序号|一级分类|品名|最低价|平均价|'
                                                            '最高价|产地|单位|发布日期\n')
            for x in range(0, len(jsn_data['list'])):
                fp.write(str(x + 1) + '|' + jsn_data['list'][x]['prodCat'] + '|' + jsn_data['list'][x][
                    'prodName'] +
                         '|' + jsn_data['list'][x]['lowPrice'] + '|' + jsn_data['list'][x]['avgPrice'] +
                         '|' + jsn_data['list'][x]['highPrice'] + '|' + jsn_data['list'][x]['place'] +
                         '|' + jsn_data['list'][x]['unitInfo'] + '|' +
                         str(jsn_data['list'][x]['pubDate'].split(' ')[0]) + '\n')


xfd = XinFaDi()
while True:
    seq_num = xfd.view_infos()
    if seq_num.strip().upper() == 'Q':
        break
    jsn_data = xfd.send_infos(seq_num)
    xfd.show_rst(jsn_data)
    xfd.save(jsn_data, seq_num)
